package controller

import (
	"fmt"
	"goWeb/bookStore/dao"
	"goWeb/bookStore/model"
	"html/template"
	"net/http"
	"strconv"
)

func GetBooks(w http.ResponseWriter, r *http.Request) {
	pageNo := r.FormValue("pageNo")
	if pageNo == "" {
		pageNo = "1"
	}
	page, _ := dao.GetPageBooks(pageNo, "", "")
	//books, _ := dao.GetAllBooks()
	t := template.Must(template.ParseFiles("views/pages/manager/book_manager.html"))
	t.Execute(w, page)
}

func GetAllBook(w http.ResponseWriter, r *http.Request) {
	pageNo := r.FormValue("pageNo")
	if pageNo == "" {
		pageNo = "1"
	}
	page, _ := dao.GetPageBooks(pageNo, "", "")
	//books, _ := dao.GetAllBooks()
	t := template.Must(template.ParseFiles("views/index.html"))
	t.Execute(w, page)
}

//根据价格获取所有图书
func GetBookByPrice(w http.ResponseWriter, r *http.Request) {
	pageNo := r.FormValue("pageNo")
	if pageNo == "" {
		pageNo = "1"
	}

	minPrice := r.FormValue("minPrice")
	maxPrice := r.FormValue("maxPrice")
	var page *model.Page

	if minPrice == "" && maxPrice == "" {
		page, _ = dao.GetPageBooks(pageNo, "", "")
	} else {
		page, _ = dao.GetPageBooks(pageNo, minPrice, maxPrice)
		page.MinPrice = minPrice
		page.MaxPrice = maxPrice
	}

	flag, session := dao.IsLogin(r)
	if flag {
		page.IsLogin = true
		page.Username = session.Username
	}

	//books, _ := dao.GetAllBooks()
	t := template.Must(template.ParseFiles("views/index.html"))
	t.Execute(w, page)
}

func AddOrUpdateBooks(w http.ResponseWriter, r *http.Request) {
	id := r.PostFormValue("id")
	title := r.PostFormValue("title")
	price := r.PostFormValue("price")
	author := r.PostFormValue("author")
	sales := r.PostFormValue("sales")
	stock := r.PostFormValue("stock")
	fPrice, _ := strconv.ParseFloat(price, 64)
	iSales, _ := strconv.ParseInt(sales, 10, 64)
	istock, _ := strconv.ParseInt(stock, 10, 64)
	book := &model.Book{
		Title:    title,
		Price:    fPrice,
		Author:   author,
		Sales:    int(iSales),
		Stock:    int(istock),
		Img_path: "/static/img/default.jpg",
	}
	if id != "" {
		//更新图书
		Intid, _ := strconv.ParseInt(id, 10, 64)
		book.Id = int(Intid)
		dao.UpdateBook(book)
	} else {
		//新增图书
		dao.AddBook(book)
	}

	GetBooks(w, r)
}

//删除图书
func DelBook(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	Intid, _ := strconv.ParseInt(id, 10, 64)
	err := dao.DelBook(int(Intid))
	if err != nil {
		fmt.Println(err)
	}
	GetBooks(w, r)
}

//去修改图书的页面
func ToUpdateBook(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	Intid, _ := strconv.ParseInt(id, 10, 64)
	if id != "" {
		book := dao.GetBookById(int(Intid))
		t := template.Must(template.ParseFiles("views/pages/manager/book_edit.html"))
		t.Execute(w, book)
	} else {
		t := template.Must(template.ParseFiles("views/pages/manager/book_edit.html"))
		t.Execute(w, "")
	}

}
